import { FC, useState, useEffect } from "react";
import { View, Image } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { AtImagePicker, AtImagePickerProps } from "taro-ui";
import { fetchPostImage } from "../../api";
import "./index.scss";
export interface UploadItemProps {
  width?: string;
  height?: string;
  showAddBtn?: boolean;
  // onChange?: (files: Object) => void;
  onImageChange?: (files: File) => void;
  // onImageFail?: (msg: string) => void;
  // onClick?: (index: number, file: Object) => void;
  // onImageClick?: (index: number, file: Object) => void;
}

export type UploadProps = UploadItemProps;

export const Upload: FC<UploadProps> = (props) => {
  const [src, setSrc] = useState<string>("");
  const [files, setFiles] = useState<any[]>([]);
  const [showAddBtn, setShowAddBtn] = useState(true);
  const { width, height, onImageChange } = props;

  const onChange = (files: any) => {
    console.log("files:", files);
    setFiles([...files]);
    if (!files.length) {
      setShowAddBtn(false);
      return;
    }

    // 微信自带的图片上传方式，需要传递自己的接口
    // 借助了taro-ui上传组件。如果不借助taro-ui的选择图片的能力的话，我们还需要一个api,
    // 选择图片api wx.chooseImage(Object object)
    Taro.uploadFile({
      url: "http://localhost:3000/api/wx/uploadimg",
      name: "file", // key
      filePath: files[0].url, // 图片路径
      formData: {
        user: "test",
      },
      success(res) {
        // 成功回调
        console.log("res:", JSON.parse(res.data));
        setSrc(JSON.parse(res.data).data.url);
      },
    });

    // Taro.chooseImage({
    //   count: 2,
    //   success(res) {
    //     console.log("res:", res);
    //   },
    // });
    // const formData = new FormData();
    // formData.append("file", files[0]);

    // fetchPostImage(formData).then((res) => {
    //   console.log("res:", res);
    // });

    setShowAddBtn(true);
    onImageChange && onImageChange(files);
  };
  const onImageClick = (index: number, file: Object) => {
    console.log("index:", index, file);
    // onClick && onClick(index, file);
    // new FormData();
  };
  const onFail = (msg: string) => {
    console.log("msg:", msg);
    // onImageFail && onImageFail(msg);
  };
  return (
    <View style={{ width, height }}>
      <Image src={src}></Image>
      <AtImagePicker
        onImageClick={onImageClick}
        files={files}
        showAddBtn={showAddBtn}
        onFail={onFail}
        onChange={onChange}
      />
    </View>
  );
};

Upload.defaultProps = {
  // with: "30rpx",
  // height: "30rpx",
};

export default Upload;
